package com.deep.cart.service.Impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.deep.cart.feign.ProductFeignService;
import com.deep.cart.interceptor.CartInterceptor;
import com.deep.cart.model.dto.UserInfoDTO;
import com.deep.cart.model.vo.CartItemVO;
import com.deep.cart.model.vo.CartVO;
import com.deep.cart.model.vo.SkuInfoVO;
import com.deep.cart.service.CartService;
import com.deep.common.model.constant.CartConstant;
import com.deep.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

/**
 * @author Deep
 * @date 2022/2/9
 */
@Slf4j
@Service
public class CartServiceImpl implements CartService {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private ThreadPoolExecutor executor;

    @Autowired
    private ProductFeignService productFeignService;

    @Override
    public CartVO getCart() throws ExecutionException, InterruptedException {
        CartVO cartVO = new CartVO();

        // 快速得到用户信息：id,user-key
        UserInfoDTO userInfoDTO = CartInterceptor.userInfoDTOThreadLocal.get();
        log.info("用户信息:{}", userInfoDTO);
        if (userInfoDTO.getUserId() != null) {
            // 用户已登录
            // 用户登录cartKey
            String cartKey = CartConstant.CART_PREFIX + userInfoDTO.getUserId();
            // 用户未登录temptCartKey
            String temptCartKey = CartConstant.CART_PREFIX + userInfoDTO.getUserKey();   // 若商品未存储到指定用户后30天后失效
            List<CartItemVO> tempCartItems = getCartItems(temptCartKey);    // 获取临时购物车数据
            // 临时购物车数据未合并
            if (tempCartItems != null && tempCartItems.size() > 0) {
                // 合并临时购物车数据
                for (CartItemVO tempCartItem : tempCartItems) {
                    addToCart(tempCartItem.getSkuId(), tempCartItem.getCount());
                }
                // 清除临时购物车数据
                clearCartInfo(temptCartKey);
            }
            // 获取(合并后)购物车所有数据
            List<CartItemVO> cartItems = getCartItems(cartKey);
            cartVO.setItems(cartItems);
        } else {
            // 用户未登录
            // 用户未登录temptCartKey
            String temptCartKey = CartConstant.CART_PREFIX + userInfoDTO.getUserKey();   // 若商品未存储到指定用户后30天后失效
            // 获取未登录用户购物车所有数据
            List<CartItemVO> cartItems = getCartItems(temptCartKey);
            cartVO.setItems(cartItems);
        }
        return cartVO;
    }

    @Override
    public CartItemVO addToCart(Long skuId, Integer num) throws ExecutionException, InterruptedException {
        // 拿到要操作的购物车信息【cartOps就相当于绑定了当前用户购物车数据的hash】
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        // 判断Redis是否有该商品的信息（有的话直接对该商品进行加减操作）
        String productRedisValue = (String) cartOps.get(skuId.toString());
        // 没有就添加数据
        if (!StringUtils.hasLength(productRedisValue)) {
            // 2、添加新的商品到购物车(redis)
            CartItemVO cartItem = new CartItemVO();
            // 异步查询商品信息
            CompletableFuture<Void> getSkuInfoFuture = CompletableFuture.runAsync(() -> {
                // 远程查询
                R productSkuInfo = productFeignService.info(skuId);
                SkuInfoVO skuInfo = productSkuInfo.getData("skuInfo", new TypeReference<SkuInfoVO>() {
                });
                // 数据赋值操作
                cartItem.setSkuId(skuInfo.getSkuId());
                cartItem.setTitle(skuInfo.getSkuTitle());
                cartItem.setImage(skuInfo.getSkuDefaultImg());
                cartItem.setPrice(skuInfo.getPrice());
                cartItem.setCount(num);
                cartItem.setCheck(true);
            }, executor);

            // 异步查询商品属性信息
            CompletableFuture<Void> getSkuAttrValuesFuture = CompletableFuture.runAsync(() -> {
                // 远程查询
                List<String> skuSaleAttrValues = productFeignService.getSkuSaleAttrValues(skuId);
                cartItem.setSkuAttrValues(skuSaleAttrValues);
            }, executor);
            // 等待所有的异步任务全部完成
            CompletableFuture.allOf(getSkuInfoFuture, getSkuAttrValuesFuture).get();

            // 存入redis
            String cartItemJson = JSON.toJSONString(cartItem);
            cartOps.put(skuId.toString(), cartItemJson);

            return cartItem;
        } else {
            // 购物车有此商品，修改数量即可
            CartItemVO cartItemVO = JSON.parseObject(productRedisValue, CartItemVO.class);
            cartItemVO.setCount(cartItemVO.getCount() + num);
            // 修改redis的数据
            String cartItemJson = JSON.toJSONString(cartItemVO);
            cartOps.put(skuId.toString(), cartItemJson);
            return cartItemVO;
        }
    }

    @Override
    public CartItemVO getCartItem(Long skuId) {
        Assert.notNull(skuId, "skuId不能为空!");

        // 拿到要操作的购物车信息
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String redisValue = (String) cartOps.get(skuId.toString());
        CartItemVO cartItemVO = JSON.parseObject(redisValue, CartItemVO.class);

        return cartItemVO;
    }

    @Override
    public List<CartItemVO> getUserCartItems() {
        UserInfoDTO userInfoDTO = CartInterceptor.userInfoDTOThreadLocal.get();

        if (userInfoDTO != null && userInfoDTO.getUserId() != null) {
            String cartKey = CartConstant.CART_PREFIX + userInfoDTO.getUserId();
            List<CartItemVO> cartItems = getCartItems(cartKey);
            if (cartItems != null && cartItems.size() > 0) {
                // 从数据库中获取商品最新价格
                //TODO 性能优化
                List<CartItemVO> cartItemVOS = cartItems.stream()
                        .filter(CartItemVO::getCheck)
                        .map(item -> {
                            BigDecimal price = productFeignService.getPrice(item.getSkuId());
                            item.setPrice(price);
                            return item;
                        }).collect(Collectors.toList());
                return cartItemVOS;
            }
        }
        return null;
    }

    /**
     * 对redis绑定hash操作（以后每次操作，都是对该key进行操作）
     */
    private BoundHashOperations<String, Object, Object> getCartOps() {
        // 当前用户信息
        UserInfoDTO userInfoTo = CartInterceptor.userInfoDTOThreadLocal.get();
        String cartKey = "";
        if (userInfoTo.getUserId() != null) {
            // mall:cart:1
            cartKey = CartConstant.CART_PREFIX + userInfoTo.getUserId();
        } else {
            // 用户未登录
            cartKey = CartConstant.CART_PREFIX + userInfoTo.getUserKey();
        }
        // 绑定指定的key操作Redis
        BoundHashOperations<String, Object, Object> operations = redisTemplate.boundHashOps(cartKey);
        return operations;
    }

    /**
     * 获取购物车里面的数据（登录/未登录）
     *
     * @param cartKey userId或temptCartKey
     * @return
     */
    private List<CartItemVO> getCartItems(String cartKey) {
        // 获取购物车里面的所有商品
        BoundHashOperations<String, Object, Object> operations = redisTemplate.boundHashOps(cartKey);
        List<Object> values = operations.values();
        if (values != null && values.size() > 0) {
            List<CartItemVO> cartItemVoStream = values.stream().map((obj) -> {
                String str = (String) obj;
                CartItemVO cartItem = JSON.parseObject(str, CartItemVO.class);
                return cartItem;
            }).collect(Collectors.toList());
            return cartItemVoStream;
        }
        return null;
    }

    /**
     * 清除临时购物车数据
     */
    private void clearCartInfo(String temptCartKey) {
        redisTemplate.delete(temptCartKey);
    }
}
